<template>
  <div class="profile-layout">
    <!-- Main Content -->
    <main class="main-content">
      <div class="content-container">
        
        <!-- A. Hero Section -->
        <section id="overview" class="hero-section">
          <div class="hero-card">
            <!-- User Info -->
            <div class="user-profile">
              <div class="avatar-wrapper">
                <img v-if="avatar" :src="avatar" class="avatar-img" alt="Avatar" />
                <div v-else class="avatar-placeholder">🌱</div>
                <div class="level-badge">Lv.{{ level }}</div>
              </div>
              <div class="user-details">
                <h2 class="nickname">{{ nickname || '低碳用户' }}</h2>
                <p class="user-title">低碳先锋</p>
                <button 
                  class="checkin-btn" 
                  :class="{ 'checked': isCheckedIn }"
                  @click="handleCheckin"
                  :disabled="isCheckedIn"
                >
                  {{ isCheckedIn ? '已签到' : '立即签到' }}
                </button>
              </div>
            </div>

            <!-- Stats Grid -->
            <div class="hero-stats">
              <div class="stat-item">
                <div class="stat-icon icon-green">🌱</div>
                <div class="stat-info">
                  <div class="stat-value">{{ carbonTarget.toFixed(2) }} <span class="unit">kg</span></div>
                  <div class="stat-label">累计减碳</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon icon-amber">💰</div>
                <div class="stat-info">
                  <div class="stat-value">{{ points }}</div>
                  <div class="stat-label">当前积分</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon icon-blue">🏅</div>
                <div class="stat-info">
                  <div class="stat-value">{{ badgesCount }}</div>
                  <div class="stat-label">获得徽章</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon icon-purple">📊</div>
                <div class="stat-info">
                  <div class="stat-value">{{ myRank !== null ? myRank + 1 : '--' }}</div>
                  <div class="stat-label">我的排名</div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- B. Charts & Tasks Grid -->
        <div class="grid-section">
          <!-- Left: Charts -->
          <section id="analysis" class="chart-card card">
            <div class="card-header">
              <h3 class="card-title">减碳趋势</h3>
              <div class="tab-switch">
                <button 
                  class="tab-btn" 
                  :class="{ active: chartPeriod === 'week' }"
                  @click="chartPeriod = 'week'"
                >周</button>
                <button 
                  class="tab-btn" 
                  :class="{ active: chartPeriod === 'month' }"
                  @click="chartPeriod = 'month'"
                >月</button>
              </div>
            </div>
            <div class="chart-body">
              <div ref="trendChartEl" class="echart-container"></div>
            </div>
          </section>

          <!-- Right: Tasks -->
          <section id="tasks" class="tasks-card card">
            <div class="card-header">
              <h3 class="card-title">今日任务</h3>
              <span class="task-count">{{ completedTasksCount }}/{{ tasksList.length }}</span>
            </div>
            <div class="tasks-list">
              <div v-for="task in tasksList" :key="task.id" class="task-item">
                <div class="task-info">
                  <div class="task-header">
                    <span class="task-name">{{ task.title }}</span>
                    <span class="task-reward">+{{ task.points }}</span>
                  </div>
                  <div class="progress-bar-bg">
                    <div 
                      class="progress-bar-fill" 
                      :style="{ width: (task.progress / task.target * 100) + '%' }"
                    ></div>
                  </div>
                  <div class="task-meta">
                    {{ task.progress }} / {{ task.target }}
                  </div>
                </div>
                <button 
                  v-if="!task.done" 
                  class="task-action-btn" 
                  @click="doTask(task)"
                >
                  完成
                </button>
                <div v-else class="task-done-icon">✅</div>
              </div>
            </div>
          </section>
        </div>

        <!-- C. History Section -->
        <section id="history" class="history-section card">
          <div class="card-header border-b">
            <div class="history-tabs">
              <button 
                class="history-tab" 
                :class="{ active: historyTab === 'points' }"
                @click="historyTab = 'points'"
              >
                积分记录
              </button>
              <button 
                class="history-tab" 
                :class="{ active: historyTab === 'activities' }"
                @click="historyTab = 'activities'"
              >
                动态记录
              </button>
            </div>
          </div>
          <div class="history-list-container">
            <div class="history-list">
              <template v-if="historyTab === 'points'">
                <div v-for="log in pointsLog" :key="log.id" class="history-item">
                  <div class="history-left">
                    <div class="history-title">{{ log.title }}</div>
                    <div class="history-time">{{ log.time }}</div>
                  </div>
                  <div class="history-amount" :class="{ 'positive': log.delta > 0 }">
                    {{ log.delta > 0 ? '+' : '' }}{{ log.delta }}
                  </div>
                </div>
                <div v-if="pointsLog.length === 0" class="empty-state">暂无积分记录</div>
              </template>
              <template v-else>
                 <div v-for="feed in feedList" :key="feed.id" class="history-item">
                  <div class="history-left">
                    <div class="history-title">{{ feed.text }}</div>
                    <div class="history-time">{{ feed.time }}</div>
                  </div>
                </div>
                 <div v-if="feedList.length === 0" class="empty-state">暂无动态</div>
              </template>
            </div>
          </div>
        </section>

      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, inject, watch } from 'vue'
import * as echarts from 'echarts'
import { getReductionStatistics, getTrend } from '../api/carbon'
import { getCurrentUser, getUserStatistics, getPointTransactions, checkin, getUserLeaderboard, getDailyTasks, completeTask } from '../api/user'
import { getUserPosts } from '../api/community'
import { useDailyLimits } from '../composables/useDailyLimits'

// --- State ---
const nickname = ref('')
const avatar = ref('')
const level = ref(1)
const points = ref(0)
const carbonTarget = ref(0)
const badgesCount = ref(0)
const myRank = ref<number|null>(null)

const chartPeriod = ref<'week'|'month'>('week')
const historyTab = ref<'points'|'activities'>('points')
const trendChartEl = ref<HTMLElement|null>(null)
let trendChart: echarts.ECharts | null = null

const { canHit, remainingOf, hit } = useDailyLimits()
const triggerPointsToast = inject<((delta:number)=>void)|null>('triggerPointsToast', null)

// --- Mock Data & Logic ---
const tasksList = reactive<any[]>([])

const completedTasksCount = computed(() => tasksList.filter(t => t.done).length)

const pointsLog = reactive<{id:number;title:string;time:string;delta:number}[]>([])
const feedList = reactive<{id:number;text:string;time:string}[]>([])

const isCheckedIn = computed(() => remainingOf('checkin', 1) === 0)

// --- Methods ---
const handleCheckin = async () => {
  if (isCheckedIn.value) return
  try {
    const resp: any = await checkin()
    const delta = Number(resp?.data?.delta ?? 5)
    hit('checkin')
    points.value += delta
    pointsLog.unshift({ id: Date.now(), title: '每日签到', time: '刚刚', delta })
    if (triggerPointsToast) triggerPointsToast(delta)
    toast(`签到成功 +${delta}积分`)
  } catch {
    // Fallback mock
    hit('checkin')
    points.value += 5
    pointsLog.unshift({ id: Date.now(), title: '每日签到', time: '刚刚', delta: 5 })
    if (triggerPointsToast) triggerPointsToast(5)
    toast('签到成功 +5积分')
  }
}

const doTask = async (task: any) => {
  if (task.done) return
  try {
    await completeTask(task.id)
    task.done = true
    task.progress = task.target
    points.value += task.points
    pointsLog.unshift({ id: Date.now(), title: `完成任务: ${task.title}`, time: '刚刚', delta: task.points })
    if (triggerPointsToast) triggerPointsToast(task.points)
    toast(`完成 ${task.title} +${task.points}积分`)
    saveTaskProgress()
  } catch (e) {
    console.error('Failed to complete task', e)
    toast('任务完成失败，请重试')
  }
}

const toast = (msg: string) => {
  const el = document.createElement('div')
  el.textContent = msg
  el.style.cssText = `
    position: fixed; left: 50%; top: 20px; transform: translateX(-50%);
    padding: 10px 20px; background: #10B981; color: white;
    border-radius: 8px; z-index: 10000; box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    font-size: 14px; transition: opacity 0.3s;
  `
  document.body.appendChild(el)
  setTimeout(() => {
    el.style.opacity = '0'
    setTimeout(() => el.remove(), 300)
  }, 2000)
}

// --- Chart ---
const initChart = () => {
  if (!trendChartEl.value) return
  trendChart = echarts.init(trendChartEl.value)
  updateChartData()
}

const updateChartData = async () => {
  if (!trendChart) return
  trendChart.showLoading()
  
  try {
    const days = chartPeriod.value === 'week' ? 7 : 30
    const res: any = await getTrend({ days })
    
    let xData: string[] = []
    let sData: number[] = []
    
    if (res?.data && Array.isArray(res.data)) {
       // Assuming backend returns [{date: '...', value: ...}, ...]
       xData = res.data.map((d:any) => {
         const date = new Date(d.date || d.record_date)
         return `${date.getMonth()+1}-${date.getDate()}`
       })
       sData = res.data.map((d:any) => Number(d.total_reduction || d.value || 0))
    } else {
       // Fallback mock if no data
       const isWeek = chartPeriod.value === 'week'
       xData = isWeek ? ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] : ['1日', '5日', '10日', '15日', '20日', '25日', '30日']
       sData = isWeek ? [12, 15, 8, 22, 18, 25, 30] : [50, 60, 55, 80, 70, 90, 100]
    }
    
    const option = {
      tooltip: { trigger: 'axis' },
      grid: { top: 20, right: 20, bottom: 30, left: 40 },
      xAxis: { type: 'category', data: xData, axisLine: { lineStyle: { color: '#ccc' } } },
      yAxis: { type: 'value', splitLine: { lineStyle: { type: 'dashed', color: '#eee' } } },
      series: [{
        data: sData,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: { color: '#10B981' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(16, 185, 129, 0.2)' },
            { offset: 1, color: 'rgba(16, 185, 129, 0)' }
          ])
        }
      }]
    }
    trendChart.setOption(option)
  } catch (e) {
    console.error('Chart data error', e)
  } finally {
    trendChart.hideLoading()
  }
}

watch(chartPeriod, () => {
  updateChartData()
})

// --- Lifecycle ---
onMounted(async () => {
  // Fetch User Info
  try {
    const u: any = await getCurrentUser()
    if (u?.data) {
      nickname.value = u.data.username || u.data.nickname
      avatar.value = u.data.avatar_url || u.data.avatar
      points.value = Number(u.data.points || 0)
      level.value = Number(u.data.level || 1)
      badgesCount.value = Number(u.data.badges_count || 0)
    }
  } catch (e) { console.error(e) }

  try {
    const s: any = await getReductionStatistics({})
    carbonTarget.value = parseFloat(s?.data?.total_reduced || '0') || 0
  } catch (e) {}

  try {
    const lb: any = await getUserLeaderboard(1, 'all') // Check rank
    if (lb?.my_rank) myRank.value = lb.my_rank
  } catch (e) {}

  // Fetch Points Log
  try {
    const tx: any = await getPointTransactions(1, 20)
    if (tx?.data?.items || Array.isArray(tx?.data)) {
      const items = Array.isArray(tx?.data) ? tx.data : tx.data.items
      pointsLog.splice(0, pointsLog.length, ...items.map((i: any) => ({
        id: i.id,
        title: i.reason || i.description || '积分变动',
        time: i.created_at ? new Date(i.created_at).toLocaleString() : '近期',
        delta: Number(i.amount || i.delta || 0)
      })))
    }
  } catch (e) {}

  // Fetch User Posts (Dynamic Record)
  try {
    const posts: any = await getUserPosts({ limit: 20 })
    if (posts?.data?.results || Array.isArray(posts?.data)) {
      const items = Array.isArray(posts?.data) ? posts.data : posts.data.results
      feedList.splice(0, feedList.length, ...items.map((p: any) => ({
        id: p.id,
        text: p.title || p.content?.substring(0, 30) || '发布了动态',
        time: p.created_at ? new Date(p.created_at).toLocaleString() : '近期'
      })))
    } else {
      // Keep mock if empty or fail, or clear it
       if (feedList.length === 0) {
         feedList.push(
          { id: 1, text: '完成了“垃圾分类”任务', time: '2小时前' },
          { id: 2, text: '兑换了“环保购物袋”', time: '昨天' },
          { id: 3, text: '获得了“低碳先锋”徽章', time: '3天前' }
        )
       }
    }
  } catch (e) {
    // Keep mock on error
  }

  // Fetch Daily Tasks
  try {
    const tasks: any = await getDailyTasks()
    console.log('[Profile] Raw tasks response:', tasks)
    
    let list: any[] = []
    
    // 健壮的解析逻辑，处理各种可能的返回结构
    if (Array.isArray(tasks)) {
      list = tasks
    } else if (tasks?.data && Array.isArray(tasks.data)) {
      list = tasks.data
    } else if (tasks?.data?.tasks && Array.isArray(tasks.data.tasks)) {
      list = tasks.data.tasks
    } else if (tasks?.data?.items && Array.isArray(tasks.data.items)) {
      list = tasks.data.items
    } else if (tasks?.tasks && Array.isArray(tasks.tasks)) {
      list = tasks.tasks
    } else if (tasks?.items && Array.isArray(tasks.items)) {
      list = tasks.items
    }
    
    console.log('[Profile] Parsed tasks list:', list)

    if (list && list.length > 0) {
      tasksList.splice(0, tasksList.length, ...list.map((t: any) => ({
        id: t.id,
        title: t.title || t.name || '未命名任务',
        points: t.points || t.reward || 0,
        done: t.status === 'completed' || t.done || false,
        progress: t.progress || (t.done ? 1 : 0),
        target: t.target || 1
      })))
      applySavedTaskProgress()
    } else {
      console.log('[Profile] No tasks found in response')
      // 如果确实没有任务，不抛出错误，而是保持空列表或使用Mock（这里为了演示效果，保留Mock逻辑）
       if (tasksList.length === 0) {
         console.log('[Profile] Using fallback mock data')
         throw new Error('No tasks found, triggering fallback')
       }
    }
  } catch (e) {
    console.warn('Fetch tasks failed or empty, using mock:', e)
    // Fallback to mock if API fails or returns empty
    if (tasksList.length === 0) {
      tasksList.splice(0, tasksList.length, 
        { id: 101, title: '步行 3km', points: 10, done: false, progress: 2.5, target: 3 },
        { id: 102, title: '骑行 5km', points: 15, done: false, progress: 1, target: 5 },
        { id: 103, title: '垃圾分类', points: 5, done: false, progress: 1, target: 1 }
      )
    }
  }

  setTimeout(initChart, 100)
  window.addEventListener('resize', () => trendChart?.resize())
})

const TASK_PROGRESS_KEY = 'dailyTasksProgress'
const todayStr = () => {
  const d = new Date()
  const y = d.getFullYear()
  const m = String(d.getMonth()+1).padStart(2,'0')
  const day = String(d.getDate()).padStart(2,'0')
  return `${y}-${m}-${day}`
}
const loadTaskProgress = (): { date: string; completedIds: number[] } | null => {
  try {
    const raw = localStorage.getItem(TASK_PROGRESS_KEY)
    if (!raw) return null
    const obj = JSON.parse(raw)
    return obj && typeof obj === 'object' ? obj : null
  } catch { return null }
}
const applySavedTaskProgress = () => {
  const saved = loadTaskProgress()
  if (!saved) return
  if (saved.date !== todayStr()) {
    localStorage.removeItem(TASK_PROGRESS_KEY)
    return
  }
  const set = new Set(saved.completedIds)
  tasksList.forEach(t => {
    if (set.has(Number(t.id))) {
      t.done = true
      t.progress = t.target
    }
  })
}
const saveTaskProgress = () => {
  const completedIds = tasksList.filter(t => t.done).map(t => Number(t.id))
  const payload = { date: todayStr(), completedIds }
  try { localStorage.setItem(TASK_PROGRESS_KEY, JSON.stringify(payload)) } catch {}
}
</script>

<style scoped>
/* Layout */
.profile-layout {
  display: flex;
  min-height: calc(100vh - 60px); /* Adjust based on navbar height if present */
  background-color: #F5F7F5; /* Sage Green Light */
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  justify-content: center;
}

/* Main Content */
.main-content {
  width: 100%;
  max-width: 1400px; /* Limit max width for better readability on large screens */
  padding: 24px;
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* Cards Generic */
.card {
  background: white;
  border-radius: 16px; /* rounded-xl */
  box-shadow: 0 1px 3px rgba(0,0,0,0.05); /* shadow-sm */
  padding: 20px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #1F2937;
  margin: 0;
}

/* Hero Section */
.hero-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  padding: 32px;
  gap: 40px;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-shrink: 0;
  min-width: 280px;
  padding-right: 40px;
  border-right: 1px solid #F3F4F6;
}

.avatar-wrapper {
  position: relative;
  width: 80px;
  height: 80px;
}

.avatar-img, .avatar-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  background: #E0E7FF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}


.level-badge {
  position: absolute;
  bottom: -4px;
  left: 50%;
  transform: translateX(-50%);
  background: #10B981;
  color: white;
  font-size: 10px;
  padding: 2px 8px;
  border-radius: 10px;
  white-space: nowrap;
  border: 2px solid white;
  z-index: 2;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nickname {
  font-size: 24px;
  font-weight: bold;
  color: #111827;
  margin: 0;
}

.user-title {
  color: #6B7280;
  font-size: 14px;
}

.checkin-btn {
  margin-top: 8px;
  padding: 6px 16px;
  background: #10B981;
  color: white;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

.checkin-btn:hover { background: #059669; }
.checkin-btn.checked { background: #D1FAE5; color: #059669; cursor: default; }

.hero-stats {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 8px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-bottom: 4px;
}
.icon-green { background: #ECFDF5; color: #10B981; }
.icon-amber { background: #FFFBEB; color: #F59E0B; }
.icon-blue { background: #EFF6FF; color: #3B82F6; }
.icon-purple { background: #F5F3FF; color: #8B5CF6; }

.stat-value {
  font-size: 20px;
  font-weight: 700;
  color: #111827;
}
.stat-value .unit { font-size: 12px; color: #9CA3AF; font-weight: normal; }
.stat-label { font-size: 13px; color: #6B7280; }

/* Grid Section */
.grid-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

/* Charts */
.chart-card {
  min-height: 300px;
  display: flex;
  flex-direction: column;
}

.tab-switch {
  background: #F3F4F6;
  padding: 4px;
  border-radius: 8px;
  display: flex;
}

.tab-btn {
  padding: 4px 12px;
  border-radius: 6px;
  border: none;
  background: transparent;
  font-size: 12px;
  color: #6B7280;
  cursor: pointer;
}

.tab-btn.active {
  background: white;
  color: #111827;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.chart-body {
  flex: 1;
  position: relative;
  min-height: 240px;
}
.echart-container { width: 100%; height: 100%; }

/* Tasks */
.tasks-card {
  display: flex;
  flex-direction: column;
}

.task-count {
  background: #ECFDF5;
  color: #059669;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.tasks-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.task-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.task-reward { color: #F59E0B; font-weight: bold; }

.progress-bar-bg {
  height: 6px;
  background: #F3F4F6;
  border-radius: 3px;
  overflow: hidden;
}

.progress-bar-fill {
  height: 100%;
  background: #10B981;
  border-radius: 3px;
  transition: width 0.3s;
}

.task-meta { font-size: 11px; color: #9CA3AF; }

.task-action-btn {
  padding: 6px 12px;
  border: 1px solid #10B981;
  color: #10B981;
  background: white;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
}
.task-action-btn:hover { background: #ECFDF5; }
.task-done-icon { font-size: 18px; color: #10B981; }

/* History */
.history-section {
  /* Removed min-height to allow auto fit */
}

.history-tabs {
  display: flex;
  gap: 24px;
}

.history-tab {
  padding: 0 0 12px 0;
  border: none;
  background: none;
  font-size: 15px;
  font-weight: 500;
  color: #6B7280;
  cursor: pointer;
  position: relative;
}

.history-tab.active {
  color: #10B981;
}

.history-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: #10B981;
}

.history-list-container {
  max-height: 400px; /* Fixed height for scrolling */
  overflow-y: auto;
  padding-top: 16px;
}

/* Custom Scrollbar */
.history-list-container::-webkit-scrollbar {
  width: 6px;
}
.history-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}
.history-list-container::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}
.history-list-container::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #F3F4F6;
}
.history-item:last-child { border-bottom: none; }

.history-title {
  font-size: 14px;
  color: #374151;
  margin-bottom: 4px;
}

.history-time {
  font-size: 12px;
  color: #9CA3AF;
}

.history-amount {
  font-weight: 600;
  color: #374151;
}
.history-amount.positive { color: #F59E0B; }
.empty-state { text-align: center; color: #9CA3AF; padding: 40px; font-size: 14px; }

@media (max-width: 768px) {
  .hero-card { flex-direction: column; align-items: flex-start; padding: 20px; gap: 24px; }
  .user-profile { border-right: none; padding-right: 0; width: 100%; border-bottom: 1px solid #F3F4F6; padding-bottom: 20px; }
  .hero-stats { grid-template-columns: repeat(2, 1fr); width: 100%; }
  .grid-section { grid-template-columns: 1fr; }
}
</style>
